<?php

/**
* @file
* Contains \Drupal\libsys\Form\MarcXml2WebForm.
*/

namespace Drupal\libsys\Form;

require_once 'File/MARCXML.php';
require_once 'File/MARC.php';

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use File_MARCXML;
use File_MARC;

/**
* MarcXml to Web concerter
*/
class MarcXml2WebForm extends FormBase {
	/**
	* {@inheritdoc}
	*/
	public function getFormId() {
		return 'libsys_marcxml2web';
	}
	
	/*
         * {@inheritdoc}
	*/
	public function buildForm(array $form, FormStateInterface $form_state) {
		$form=[];
		$form['marcxmltext']=array(
			'#type'=>'textarea',
			'#title'=>$this->t('MarcXML text'),
			'#required'=>TRUE,
			'#rows'=>10,
		);

                $form['actions']['submit'] = [
                        '#type'=>'submit',
                        '#value'=>$this->t('Convert'),
                ];

		$marcxml=$form_state->getValue('marcxmltext');
		if(empty($marcxml)) return $form;
		
		try {
			$marc=new File_MARCXML($marcxml, File_MARC::SOURCE_STRING);
			$record=$marc->next();
			$rows=[];
			$form['marc']=[
				'#type'=>'table',
				'#prefix'=>'<code>',
				'#suffix'=>'</code>'
			];
			$form['marc'][]=[
				'tag'=>['#markup'=>'LDR'],
				'data'=>['#markup'=>str_replace(' ',' ',$record->getLeader())],
			];
			foreach($record->getFields() as $f) {
				if($f->isControlField()) {
					$form['marc'][]= [
						'tag'=>['#markup'=>$f->getTag()],
						'data'=>['#markup'=>str_replace(' ','&nbsp;',$f->getData())],
					];
				} else {
					$t='';
					foreach($f->getSubFields() as $data) {
						$t.='|'.$data->getCode().$data->getData();
					}
					$t=str_replace(' ','&nbsp;',$t);
					$form['marc'][]= [
						'tag'=>['#markup'=>$f->getTag().$f->getIndicator(1).$f->getIndicator(2)],
						'data'=>['#markup'=>$t]
					];
				}
			}
		} catch (\Exception $e) {
		}

		return $form;
	}

	/**
	* {@inheritdoc}
	*/
	public function validateForm(array &$form, FormStateInterface $form_state) {
	}

	/**
	* {@inheritdoc}
	*/
	public function submitForm(array &$form, FormStateInterface $form_state) {
		$form_state->setRebuild(TRUE);
		return;
	}

}
?>

